﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ELab.Serialization.Data;
using ELab.Client;
using ELab.QuestionAnwer;
using ELab.Message;
using ELab.Communication.Messages;

namespace ELab.Teacher.Controls
{
    public partial class ctrlQACreation : UserControl
    {
        public ELabClient TeacherControl { get; set; }
        public IEnumerable<User> Users { get; set; }

        private List<Question> Questions;
        public ctrlQACreation()
        {
            InitializeComponent();
            Questions = new List<Question>();
            QADataGridView.AllowUserToAddRows = false;
            QADataGridView.AutoGenerateColumns = false;
            QADataGridView.ColumnHeadersVisible = false;
            QADataGridView.CellMouseClick += QADataGridView_CellMouseClick;
            lbMessage.Text = string.Empty;
        }

        void QADataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            QADataGridView.BeginEdit(false);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            CollectValueGrid();
            lbMessage.Text = string.Empty;
            int qNo = 0;
            int aNo = 0;
            if (int.TryParse(txtQNo.Text, out qNo) && int.TryParse(txtANo.Text, out aNo))
            {
                if (Questions.Count > 0 && aNo != Questions[0].Answers.Length)
                {
                    int oldLength = Questions[0].Answers.Length;
                    if (aNo < oldLength)
                    {                        
                        foreach (var q in Questions)
                        {
                            List<Answer> answers = q.Answers.ToList();
                            answers.RemoveRange(aNo, oldLength - aNo);
                            q.Answers = answers.ToArray();
                        }
                    }
                    else
                    {
                        foreach (var q in Questions)
                        {
                            List<Answer> answers = q.Answers.ToList();
                            for (int i = 0; i < aNo - oldLength; i++)
                            {
                                answers.Add(new Answer());
                            }
                            q.Answers = answers.ToArray();
                        }
                    }
                }

                if (Questions.Count < qNo)
                {
                    for (int i = Questions.Count; i < qNo; i++)
                    {
                        Question q = new Question();
                        var answers = new List<Answer>();
                        for (int j = 0; j < aNo; j++)
                        {
                            answers.Add(new Answer());
                        }
                        q.Answers = answers.ToArray();
                        Questions.Add(q);
                    }
                }
                else if (Questions.Count > qNo)
                {
                    Questions.RemoveRange(qNo, Questions.Count - qNo);
                }
               
                LoadGrid();
            }
        }

        private void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }
        }

        private void LoadGrid()
        {
            QADataGridView.Columns.Clear();
            QADataGridView.Rows.Clear();
            QADataGridView.Refresh();

            for (int i = 0; i < Questions.Count; i++)
            {
                QADataGridView.Columns.Add(string.Format("Question{0}", i), string.Format("Question {0}", i));
            }

            for (int i = 0; i <= Questions[0].Answers.Length; i++)
            {
                DataGridViewRow row = new DataGridViewRow();
                for (int j = 0; j < Questions.Count; j++)
                {
                    DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
                    if (i == 0)
                    {
                        cell.Value = string.IsNullOrEmpty(Questions[j].QuestionValue) ? string.Format("Question {0}", j+1) : Questions[j].QuestionValue;
                    }
                    row.Cells.Add(cell);
                }
                QADataGridView.Rows.Add(row);
            }
            QADataGridView.Refresh();
        }

        private void CollectValueGrid()
        {
            if (QADataGridView.Rows.Count > 0)
            {
                for (int i = 0; i < QADataGridView.Rows.Count; i++)
                {
                    var row = QADataGridView.Rows[i];
                    for (int j = 0; j < Questions.Count; j++)
                    {
                        if (i == 0)
                        {
                            Questions[j].QuestionValue = (string)row.Cells[j].Value;
                        }
                        else
                        {
                            Questions[j].Answers[i-1].AnswerValue = (string)row.Cells[j].Value;
                        }
                    }
                }
            }
        }

        private void btnComplete_Click(object sender, EventArgs e)
        {
            CollectValueGrid();
            var examp = new LessonTest();
            examp.TimeToTest = int.Parse(txtMinute.Text) * 60 + int.Parse(txtSeconds.Text);
            examp.Questions = Questions;

            var dataArr = examp.SerializeToByteArray();

            Message.CommandType cmdType = Message.CommandType.RequestTableExample;
            CommandMessage comm = new CommandMessage { CommandType = cmdType, Body = dataArr };
            EMessage mess = new EMessage { Command = comm };

            //Cai nay nen truyen tu form Main vao
            if (TeacherControl != null)
            {
                foreach (User user in this.Users)
                {
                    var ms = TeacherControl.CreateMessage();
                    ms.DestinationApplicationName = user.UserName;
                    ms.MessageData = mess.Data;
                    ms.TransmitRule = MessageTransmitRules.NonPersistent;
                    ms.Send();
                }
            }

            lbMessage.Text = "The test lesson has been sent to the student for testing.";
            
            txtANo.Text = "0";
            txtQNo.Text = "0";
            QADataGridView.Columns.Clear();
            QADataGridView.Rows.Clear();
            QADataGridView.Refresh();
        }
    }

}
